import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('../views/Layout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { title: '控制台', icon: 'Odometer' }
      },
      {
        path: 'products',
        name: 'Products',
        component: () => import('../views/product/ProductList.vue'),
        meta: { title: '商品管理', icon: 'ShoppingBag' }
      },
      {
        path: 'products/add',
        name: 'AddProduct',
        component: () => import('../views/product/ProductForm.vue'),
        meta: { title: '添加商品', activeMenu: '/products' }
      },
      {
        path: 'products/edit/:id',
        name: 'EditProduct',
        component: () => import('../views/product/ProductForm.vue'),
        meta: { title: '编辑商品', activeMenu: '/products' },
        props: true
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('../views/order/OrderList.vue'),
        meta: { title: '订单管理', icon: 'List' }
      },
      {
        path: 'orders/:id',
        name: 'OrderDetail',
        component: () => import('../views/order/OrderDetail.vue'),
        meta: { title: '订单详情', activeMenu: '/orders' },
        props: true
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/user/UserList.vue'),
        meta: { title: '用户管理', icon: 'User' }
      },
      {
        path: 'users/:id',
        name: 'UserDetail',
        component: () => import('../views/user/UserDetail.vue'),
        meta: { title: '用户详情', activeMenu: '/users' },
        props: true
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory('/admin/'),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  const token = localStorage.getItem('admin_token')
  
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else {
    next()
  }
})

// 全局后置钩子
router.afterEach(() => {
  NProgress.done()
})

export default router